package com.cms.common.lang;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import com.cms.common.pojo.Result;


/** 处理器链（责任链模式）. */
public class HandleChain {

	/** 处理器集 */
	private List<Handle> handles;
	
	/** 处理器集当前索引 */
	private int index = -1;
	
	/** 构建处理器链 */
	public HandleChain() {
		this.handles = new ArrayList<Handle>();
	}
	
	/** 构建处理器链. */
	public HandleChain(List<Handle> handles) {
		if (handles == null) {
			this.handles = new ArrayList<Handle>();
		} else {
			this.handles = handles;
		}
	}
	
	/** 添加处理器. */
	public HandleChain addHandle(Handle handle) {
		handles.add(handle);
		return this;
	}
	
	/** 执行处理器链. */
	public void handle(Map<String,Object> params, Result result) {
		if (index >= handles.size() - 1) return;
		handles.get(++index).handle(params, result, this);
	}
	
	/** 处理器接口. */
	public static interface Handle {
		void handle(Map<String,Object> params, Result result, HandleChain chain) ;
	}

}